<template>
  <view class="container">
    <view class="header">
      <text class="title">{{ isEditMode ? '编辑现金流水' : '新增现金流水' }}</text>
    </view>
    
    <view class="form-container">
      <!-- 流水类型 -->
      <view class="form-item">
        <text class="label">流水类型 *</text>
        <picker v-model="flowType" :range="flowTypes" range-key="label" @change="onFlowTypeChange">
          <view class="picker-display">{{ getFlowTypeLabel(flowType) }}</view>
        </picker>
      </view>
      
      <!-- 金额 -->
      <view class="form-item">
        <text class="label">金额 *</text>
        <input 
          class="input" 
          type="digit" 
          v-model="amount" 
          placeholder="请输入金额"
        />
      </view>
      
      <!-- 渠道 -->
      <view class="form-item">
        <text class="label">渠道 *</text>
        <input 
          class="input" 
          type="text" 
          v-model="channel" 
          placeholder="请输入渠道（如：银行转账、交易所等）"
        />
      </view>
      
      <!-- 手续费 -->
      <view class="form-item">
        <text class="label">手续费</text>
        <input 
          class="input" 
          type="digit" 
          v-model="fee" 
          placeholder="请输入手续费（可选）"
        />
      </view>
      
      <!-- 备注 -->
      <view class="form-item">
        <text class="label">备注</text>
        <textarea 
          class="textarea" 
          v-model="note" 
          placeholder="请输入备注（可选）"
        />
      </view>
      
      <!-- 保存按钮 -->
      <button class="save-button" @click="saveRecord">保存记录</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { post, put } from '../../utils/api';

const router = useRouter();
const route = useRoute();
const flowType = ref('deposit');
const amount = ref('');
const channel = ref('');
const fee = ref('');
const note = ref('');
const isEditMode = ref(false);
const recordId = ref(null);

// 流水类型选项
const flowTypes = [
  { value: 'deposit', label: '存款' },
  { value: 'withdraw', label: '取款' },
  { value: 'fiat_in', label: '法币入金' },
  { value: 'fiat_out', label: '法币出金' }
];

// 获取流水类型标签
const getFlowTypeLabel = (value) => {
  const type = flowTypes.find(item => item.value === value);
  return type ? type.label : '';
};

// 初始化页面数据
onMounted(() => {
  // 检查是否是编辑模式
  if (route.query.mode === 'edit') {
    isEditMode.value = true;
    recordId.value = route.query.id;
    
    // 预填充表单数据
    if (route.query.flow_type) {
      flowType.value = route.query.flow_type;
    }
    if (route.query.amount) {
      amount.value = route.query.amount;
    }
    if (route.query.channel) {
      channel.value = route.query.channel;
    }
    if (route.query.fee) {
      fee.value = route.query.fee;
    }
    if (route.query.note) {
      note.value = route.query.note;
    }
  }
});

// 处理流水类型选择事件
const onFlowTypeChange = (e) => {
  flowType.value = flowTypes[e.detail.value].value;
};

// 保存记录
const saveRecord = async () => {
  // 验证输入
  if (!flowType.value) {
    uni.showToast({
      title: '请选择流水类型',
      icon: 'none'
    });
    return;
  }
  
  if (!amount.value) {
    uni.showToast({
      title: '请输入金额',
      icon: 'none'
    });
    return;
  }
  
  if (!channel.value) {
    uni.showToast({
      title: '请输入渠道',
      icon: 'none'
    });
    return;
  }
  
  // 格式化保存的数据
  const recordData = {
    flow_type: flowType.value,
    amount: parseFloat(amount.value),
    channel: channel.value,
    fee: fee.value ? parseFloat(fee.value) : 0,
    note: note.value || null
  };
  
  try {
    let res;
    
    // 根据模式选择请求方法
    if (isEditMode.value) {
      res = await put(`/api/cash-flow/${recordId.value}`, recordData);
    } else {
      res = await post('/api/cash-flow', recordData);
    }
    
    if (res.statusCode === 200 || res.statusCode === 201) {
      // 显示成功提示
      uni.showToast({
        title: isEditMode.value ? '修改成功' : '新增成功',
        icon: 'success',
        success: () => {
          // 延迟返回上一个页面
          setTimeout(() => {
            router.back();
          }, 1500);
        }
      });
    } else {
      uni.showToast({
        title: res.data?.error || (isEditMode.value ? '修改失败' : '新增失败'),
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('保存记录失败:', error);
    uni.showToast({
      title: '网络错误，保存失败',
      icon: 'none'
    });
  }
};
</script>

<style>
.container {
  padding: 12px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.form-container {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 16px;
}

.label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.input {
  width: 100%;
  height: 44px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 0 12px;
  font-size: 16px;
  box-sizing: border-box;
}

.textarea {
  width: 100%;
  min-height: 80px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 10px 12px;
  font-size: 16px;
  box-sizing: border-box;
  resize: vertical;
}

.picker-display {
  width: 100%;
  height: 44px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 0 12px;
  font-size: 16px;
  display: flex;
  align-items: center;
  background-color: #f9f9f9;
  color: #333;
  box-sizing: border-box;
}

.save-button {
  width: 100%;
  height: 44px;
  background-color: #1989fa;
  color: #fff;
  border: none;
  border-radius: 20px;
  font-size: 16px;
  font-weight: bold;
  margin-top: 20px;
}

.save-button:active {
  background-color: #096dd9;
}
</style>